import React, { useState, useEffect } from 'react';
import { View, Text, Image, TouchableOpacity, StyleSheet, ScrollView, FlatList } from 'react-native';
import { NativeEventEmitter, NativeModules } from 'react-native';

interface Device {
  id?: number;
  userId: string;
  dataType: any;
  deviceData?: any; // 根据实际数据结构定义
}


interface PCRTestData {
  algorithmNo?: number;
  deviceNo?: string;
  kitNo?: string;
  result?: string;
  resultShow: string;
  dataType: string;
  userId: string;
}



const DashboardScreen: React.FC = () => {
  const [mockTableData, setMockTableData] = useState<PCRTestData[]>([])
  const [mockDeviceData, setMockDeviceData] = useState<Device[]>([
    { id: 1,  userId: '', dataType: '' },
    { id: 2,  userId: '', dataType: '' },
    { id: 3,  userId: '', dataType: '' },
    { id: 4,  userId: '', dataType: '' },
    { id: 5,  userId: '', dataType: '' },
    { id: 6,  userId: '', dataType: '' },
    { id: 7,  userId: '', dataType: '' },
    { id: 8,  userId: '', dataType: '' }
  ]);


  // const mapReceivedDataToDevice = (receivedData: Device): Device[] => {
  //   const newDevices = [...mockDeviceData];
  //   const index = newDevices.findIndex((device) => device.userId === receivedData.userId);
  //   // 如果没有找到对应的设备，那么则对第一个userId为空的设备进行赋值
  //   if (index === -1) {
  //     const emptyDevice = newDevices.find((device) => device.userId === '');
  //     if (emptyDevice) {
  //       emptyDevice.userId = receivedData.userId;
  //       emptyDevice.dataType = receivedData.dataType;
  //     } else {
  //       const device = newDevices.find((device) => device.dataType !== 'deviceUP');
  //       if (device) {
  //         device.userId = receivedData.userId;
  //         device.dataType = receivedData.dataType;
  //       }
  //     }
  //   } else {
  //     newDevices[index].userId = receivedData.userId;
  //     newDevices[index].dataType = receivedData.dataType;
  //   }
  //   return newDevices;
  // }


  const mapReceivedDataToDevice = (receivedData: Device) => {
    const newDevices = [...mockDeviceData];
    const index = newDevices.findIndex((device) => device.userId === receivedData.userId);
    // 如果没有找到对应的设备，那么则对第一个userId为空的设备进行赋值
    if (index === -1) {
      const emptyDevice = newDevices.find((device) => device.userId === '');
      if (emptyDevice) {
        emptyDevice.userId = receivedData.userId;
        emptyDevice.dataType = receivedData.dataType;
      }
    } else {
      // 如果找到了对应的设备，那么如果是设备下线，那么则将该设备的userId置为空
      if (receivedData.dataType === 'deviceDown') {
        newDevices[index].userId = '';
        newDevices[index].dataType = '';
      }
    }
    return newDevices;
  }
  
  const handleReceivedData = (receivedData: Device) => {
    const newDevices = mapReceivedDataToDevice(receivedData);
    setMockDeviceData(newDevices);
  };

  const handleReceivedRecord = (receivedData: PCRTestData) => {
    setMockTableData((prevData) => [receivedData, ...prevData]);
  };


  useEffect(() => {
    const eventEmitter = new NativeEventEmitter(NativeModules.ToastExample);
    const eventListener = eventEmitter.addListener('EventReminder', (event) => {
      const receivedData = JSON.parse(event.eventProperty)
      console.log(receivedData)
      if (receivedData.dataType === 'deviceDown' || receivedData.dataType === 'deviceUP') {
        handleReceivedData(receivedData);
      } else {
        const data = JSON.parse(receivedData.data);
        const { resultShow, kitNo } = data;
        handleReceivedRecord({ resultShow, kitNo, dataType: receivedData.dataType, userId: receivedData.userId });
      }
    });
    return () => {
      eventListener.remove();
    };
  }, [handleReceivedData]);

  const renderDeviceCard: React.FC<{ item: Device }> = ({ item }) => (
    <TouchableOpacity
      style={styles.deviceCard}>
      {item.dataType==='deviceUP' ? <View style={styles.highlightDot} /> : <View style={styles.defaultDot} /> }
      <Text style={styles.deviceName}>{item.userId}</Text>
    </TouchableOpacity>
  );

  const renderTableData = () => (
    <View style={styles.table}>
      <View style={styles.tableRow}>
        <Text style={styles.tableHeaderCell}>设备号</Text>
        <Text style={styles.tableHeaderCell}>结果</Text>
      </View>
      {mockTableData.map((rowData, index) => (
        <View key={index} style={styles.tableRow}>
          <Text style={styles.tableCell}>{rowData.kitNo}</Text>
          <Text style={styles.tableCell}>{rowData.resultShow}</Text>
        </View>
      ))}
    </View>
  );

  const renderDeviceRows = () => {
    return (
      <FlatList
        data={mockDeviceData}
        keyExtractor={(item: Device) => item.id!.toString()}
        renderItem={({ item }) => (
          <View style={styles.deviceCardContainer}>
            {renderDeviceCard({ item })}
          </View>
        )}
        numColumns={4}
      />
    );
  };

  return (
    <ScrollView style={styles.container}>
      <ScrollView  style={{ width: "100%" }}>
        <View style={styles.content}>
          {renderDeviceRows()}
          <View style={styles.lowerSection}>
            <Text style={styles.tableTitle}>实验数据</Text>
            {renderTableData() }
          </View>
        </View>
      </ScrollView>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f0f0',
  },
  content: {
    padding: 16,
  },
  deviceRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 15,
  },
  deviceCardContainer: {
    width: '23.5%', // Each device card is smaller to fit four in a row
    marginBottom: 16,
    marginRight: 6
  },
  deviceCard: {
    borderRadius: 8,
    minHeight: 45,
    backgroundColor: '#fff',
    elevation: 10,
  },
  deviceName: {
    textAlign: 'center',
    fontSize: 12, // Smaller font size
    color: '#333',
    padding: 8,
  },
  highlightDot: {
    width: 10,
    height: 10,
    borderRadius: 4,
    backgroundColor: 'green',
    position: 'absolute',
    top: 5,
    left: 5,
  },
  defaultDot: {
    width: 10,
    height: 10,
    borderRadius: 4,
    backgroundColor: '#f6f6f6',
    position: 'absolute',
    top: 5,
    left: 5
  },

  lowerSection: {
    flex: 1,
    marginTop: 16,
  },
  tableTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  toggleTableButton: {
    color: 'blue',
    fontSize: 16,
    marginBottom: 8,
  },
  tableScrollView: {
    maxHeight: 300,
  },
  table: {
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 8,
    overflow: 'hidden',
  },
  tableRow: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderColor: '#ccc',
    backgroundColor: '#f5f5f5',
  },
  tableHeaderCell: {
    flex: 1,
    padding: 12,
    textAlign: 'center',
    fontWeight: 'bold',
    color: '#333',
  },
  tableCell: {
    flex: 1,
    padding: 12,
    textAlign: 'center',
    color: '#333',
  },
});

export default DashboardScreen;